<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use think\Config;
use think\Cookie;
use think\Hook;
use think\Session;
use app\common\library\Sms;
use fast\Random;
use think\Validate;
use app\common\model\Bank;
use app\api\model\Address;
use app\common\library\Sms as Smslib;
use app\common\library\Ems as Emslib;


/**
 * 会员中心
 */
class User extends Frontend
{

    protected $layout = 'layout';
    protected $noNeedLogin = ['login', 'register', 'third'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $auth = $this->auth;

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

        $ucenter = get_addon_info('ucenter');
        if ($ucenter && $ucenter['state']) {
            include ADDON_PATH . 'ucenter' . DS . 'uc.php';
        }

        //监听注册登录注销的事件
        Hook::add('user_login_successed', function ($user) use ($auth) {
            $expire = input('post.keeplogin') ? 30 * 86400 : 0;
            Cookie::set('uid', $user->id, $expire);
            Cookie::set('token', $auth->getToken(), $expire);
        });
        Hook::add('user_register_successed', function ($user) use ($auth) {
            Cookie::set('uid', $user->id);
            Cookie::set('token', $auth->getToken());
        });
        Hook::add('user_delete_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
        Hook::add('user_logout_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
    }

    /**
     * 会员中心
     */
    public function index()
    {
        $bank = new Bank();
        $banks=$bank->where('status',1)->where('default',1)->where('user_id',$this->auth->id)->find();
        if (empty($banks)) {
          $banks=$bank->where('status',1)->where('default',0)->where('user_id',$this->auth->id)->find();
        }
        $address = new Address();
        $addresss=$address->where('status',1)->where('default',1)->where('user_id',$this->auth->id)->find();
        if (empty($addresss)) {
            $addresss=$address->where('status',1)->where('default',0)->where('user_id',$this->auth->id)->find();
        }
       

        $this->view->assign('title', __('User center'));
        return $this->view->fetch('',['addresss'=>$addresss,'banks'=>$banks]);
    }
    public function about(){
         $phone = config('site.basic_pohne');
     return $this->view->fetch('',['phone'=>$phone]);   
    }
    public function introduce(){
        $about_intro = config('site.about_intro');
       
     return $this->view->fetch('',['about_intro'=>$about_intro]);   
    }
    public function rule(){
         $about_rule = config('site.about_rule');
     return $this->view->fetch('',['about_rule'=>$about_rule]);   
    }
    public function question_and_answer(){
          $about_anwser = config('site.about_anwser');
     return $this->view->fetch('',['about_anwser'=>$about_anwser]);   
    }
    
    /**
     * 注册会员
     */
    public function register()
    {
        $url = $this->request->request('url');
        if ($this->auth->id)
            $this->success(__('You\'ve logged in, do not login again'), $url);
        if ($this->request->isPost()) {
            $username = $this->request->post('username');
            $password = $this->request->post('password');
            $email = $this->request->post('email');
            $mobile = $this->request->post('mobile', '');
            $captcha = $this->request->post('captcha');
            $token = $this->request->post('__token__');
            $rule = [
                'username'  => 'require|length:3,30',
                'password'  => 'require|length:6,30',
                'email'     => 'require|email',
                'mobile'    => 'regex:/^1\d{10}$/',
                'captcha'   => 'require|captcha',
                '__token__' => 'token',
            ];

            $msg = [
                'username.require' => 'Username can not be empty',
                'username.length'  => 'Username must be 3 to 30 characters',
                'password.require' => 'Password can not be empty',
                'password.length'  => 'Password must be 6 to 30 characters',
                'captcha.require'  => 'Captcha can not be empty',
                'captcha.captcha'  => 'Captcha is incorrect',
                'email'            => 'Email is incorrect',
                'mobile'           => 'Mobile is incorrect',
            ];
            $data = [
                'username'  => $username,
                'password'  => $password,
                'email'     => $email,
                'mobile'    => $mobile,
                'captcha'   => $captcha,
                '__token__' => $token,
            ];
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
            }
            if ($this->auth->register($username, $password, $email, $mobile)) {
                $synchtml = '';
                ////////////////同步到Ucenter////////////////
                if (defined('UC_STATUS') && UC_STATUS) {
                    $uc = new \addons\ucenter\library\client\Client();
                    $synchtml = $uc->uc_user_synregister($this->auth->id, $password);
                }
                $this->success(__('Sign up successful') . $synchtml, $url ? $url : url('user/index'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        //判断来源
        $referer = $this->request->server('HTTP_REFERER');
        if (!$url && (strtolower(parse_url($referer, PHP_URL_HOST)) == strtolower($this->request->host()))
            && !preg_match("/(user\/login|user\/register)/i", $referer)) {
            $url = $referer;
        }
        $this->view->assign('url', $url);
        $this->view->assign('title', __('Register'));
        return $this->view->fetch();
    }

    /**
     * 会员登录
     */
    public function login()
    {
        $url = $this->request->request('url');
        if ($this->auth->id)
            $this->success(__('You\'ve logged in, do not login again'), $url);
        if ($this->request->isPost()) {
            $account = $this->request->post('account');
            $password = $this->request->post('password');
            $keeplogin = (int)$this->request->post('keeplogin');
            $token = $this->request->post('__token__');
            $rule = [
                'account'   => 'require|length:3,50',
                'password'  => 'require|length:6,30',
                '__token__' => 'token',
            ];

            $msg = [
                'account.require'  => 'Account can not be empty',
                'account.length'   => 'Account must be 3 to 50 characters',
                'password.require' => 'Password can not be empty',
                'password.length'  => 'Password must be 6 to 30 characters',
            ];
            $data = [
                'account'   => $account,
                'password'  => $password,
                '__token__' => $token,
            ];
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                return FALSE;
            }
            if ($this->auth->login($account, $password)) {
                $synchtml = '';
                ////////////////同步到Ucenter////////////////
                if (defined('UC_STATUS') && UC_STATUS) {
                    $uc = new \addons\ucenter\library\client\Client();
                    $synchtml = $uc->uc_user_synlogin($this->auth->id);
                }
                $this->success(__('Logged in successful') . $synchtml, $url ? $url : url('user/index'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        //判断来源
        $referer = $this->request->server('HTTP_REFERER');
        if (!$url && (strtolower(parse_url($referer, PHP_URL_HOST)) == strtolower($this->request->host()))
            && !preg_match("/(user\/login|user\/register)/i", $referer)) {
            $url = $referer;
        }
        $this->view->assign('url', $url);
        $this->view->assign('title', __('Login'));
        return $this->view->fetch();
    }

    /**
     * 注销登录
     */
    function logout()
    {
        //注销本站
        $this->auth->logout();
        $synchtml = '';
        ////////////////同步到Ucenter////////////////
        if (defined('UC_STATUS') && UC_STATUS) {
            $uc = new \addons\ucenter\library\client\Client();
            $synchtml = $uc->uc_user_synlogout();
        }
        $this->success(__('Logout successful') . $synchtml, url('user/index'));
    }

    /**
     * 个人信息
     */
    public function profile()
    {
        $this->view->assign('title', __('Profile'));
        return $this->view->fetch();
    }
    public function share()
    {
        $invitecode = createInvite($this->auth->id);
       
        return $this->view->fetch('',['invitecode'=>$invitecode]);
    }
    public function usdt()
    {
       
         $user = $this->auth->getUser();
        return $this->view->fetch('',['user'=>$user]);
    }
    /**
     * 修改登录密码
     */
    public function changepwd()
    {
        if ($this->request->isPost()) {
            $oldpassword = $this->request->post("oldpassword");
            $newpassword = $this->request->post("newpassword");
            $renewpassword = $this->request->post("renewpassword");
            $token = $this->request->post('__token__');
            $rule = [
                'oldpassword'   => 'require|length:6,30',
                'newpassword'   => 'require|length:6,30',
                'renewpassword' => 'require|length:6,30|confirm:newpassword',
                '__token__'     => 'token',
            ];

            $msg = [
            ];
            $data = [
                'oldpassword'   => $oldpassword,
                'newpassword'   => $newpassword,
                'renewpassword' => $renewpassword,
                '__token__'     => $token,
            ];
            $field = [
                'oldpassword'   => __('Old password'),
                'newpassword'   => __('New password'),
                'renewpassword' => __('Renew password')
            ];
            $validate = new Validate($rule, $msg, $field);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                return FALSE;
            }
            $captcha = $this->request->post("captcha");
            $userinfo = $this->auth->getUserInfo();
            if ($userinfo['mobile']) {
                $ret = Smslib::check($userinfo['mobile'], $captcha, 'resetpasswrod');
                if (!$ret) {
                    $this->error(__('验证码不正确'));
                }
            }else{
                $this->error(__('验证码不正确'));
            }

            $ret = $this->auth->changepwd($newpassword, $oldpassword);
            if ($ret) {
                $synchtml = '';
               
                if (defined('UC_STATUS') && UC_STATUS) {
                    $uc = new \addons\ucenter\library\client\Client();
                    $synchtml = $uc->uc_user_synlogout();
                }
                $this->success(__('Reset password successful') . $synchtml, url('user/index'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        $this->view->assign('title', __('Change password'));
        return $this->view->fetch();
    }
     /**
     * 修改支付密码
     */
    public function password(){
        if ($this->request->isPost()) {
            $oldpaypassword = $this->request->post("oldpaypassword");
            $newpaypassword = $this->request->post("newpaypassword");
            $confirmpaypassword = $this->request->post("confirmpaypassword");
            $token = $this->request->post('__token__');
            
            $captcha = $this->request->post("captcha");

            $userinfo = $this->auth->getUserInfo();
            if ($userinfo['mobile']) {
                $ret = Smslib::check($userinfo['mobile'], $captcha, 'resetpaypasswrod');
                if (!$ret) {
                    $this->error(__('验证码不正确'));
                }
            }else{
                $this->error(__('验证码不正确'));
            }
             if (empty($oldpaypassword)) {
                $this->error('请输入旧密码');
            }
            if (empty($newpaypassword)) {
                $this->error('请输入新密码');
            }
            if (empty($confirmpaypassword)) {
                $this->error('请输入确认新密码');
            }
            if ($newpaypassword !== $confirmpaypassword) {
                $this->error('确认密码不正确');
            }

            $ret = $this->auth->changeppwd($newpaypassword, $oldpaypassword);
            if ($ret)
            {
                $this->success(__('Reset password successful'));
            }
            else
            {
                $this->error($this->auth->getError());
            }
        }
     return $this->view->fetch();
    }
     /**
     * 重置密码
     * 
     * @param string $mobile 手机号
     * @param string $newpassword 新密码
     * @param string $captcha 验证码
     */
   
    /**
     * 获取我的银行卡列表
     * 
     */
    public function getbanks()
    {
        $bank = new Bank();
        $banks=$bank->where('status',1)->where('user_id',$this->auth->id)->order('default desc,id desc')->select();
        return $this->view->fetch('',['banks'=>$banks]);
    }
    /**
     * 添加银行卡
     * 
     */
    public function bank_card_add(){
          if ($this->request->isPost()) {
            $bank = new Bank();
            $request=array();
            $request['bankname']=$this->request->post('bankname');
            $request['bankcard']=$this->request->post('bankcard');
            $request['bankaddress']=$this->request->post('bankaddress');
            $request['realname']=$this->request->post('realname');
            $request['default']=$this->request->post('default');
            $token = $this->request->post('__token__');
             $rule = [
                'bankname'   => 'require|length:2,10',
                'bankcard'   => 'require|length:16,19',
                'bankaddress' => 'require|length:2,100',
                'realname' => 'require|length:2,10',
                '__token__'     => 'token',
            ];

            $msg = [
            ];
            $data = [
                'bankname'   => $request['bankname'],
                'bankcard'   => $request['bankcard'],
                'bankaddress' => $request['bankaddress'],
                'realname' => $request['realname'],
                '__token__'     => $token,
            ];
            $field = [
                'bankname'   => __('银行卡名称'),
                'bankcard'   => __('银行卡号'),
                'bankaddress' => __('开户地址'),
                'realname'   => __('开户人姓名'),
            ];
            $validate = new Validate($rule, $msg, $field);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                return FALSE;
            }
            $bank->user_id=$this->auth->id;
            $result = $bank->allowField(true)->validate('Bank.add')->save($request);
            if(false === $result){
                $this->error($bank->getError());
            }
            $this->success('增加成功',url('user/getbanks'));


          }


        return $this->view->fetch();
    }
    /**
     * 编辑银行卡
     * 
     */
     public function bank_update(){
        $id = $_GET['id'];
        $bank = new Bank();
        $info=$bank->where('user_id',$this->auth->id)->where('id',$id)->find();
        if (!$info) {
            $this->error('不是你的银行卡！');
        }
        if ($this->request->isPost()) {
            $request=array();
            $request['bankname']=$this->request->post('bankname');
            $request['bankcard']=$this->request->post('bankcard');
            $request['bankaddress']=$this->request->post('bankaddress');
            $request['realname']=$this->request->post('realname');
            $request['default']=$this->request->post('default');
            $token = $this->request->post('__token__');
             $rule = [
                'bankname'   => 'require|length:2,10',
                'bankcard'   => 'require|length:16,19',
                'bankaddress' => 'require|length:2,100',
                'realname' => 'require|length:2,10',
                '__token__'     => 'token',
            ];

            $msg = [
            ];
            $data = [
                'bankname'   => $request['bankname'],
                'bankcard'   => $request['bankcard'],
                'bankaddress' => $request['bankaddress'],
                'realname' => $request['realname'],
                '__token__'     => $token,
            ];
            $field = [
                'bankname'   => __('银行卡名称'),
                'bankcard'   => __('银行卡号'),
                'bankaddress' => __('开户地址'),
                'realname'   => __('开户人姓名'),
            ];
            $validate = new Validate($rule, $msg, $field);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                return FALSE;
            }
            if (empty($id)) {
                $this->error('请传入id ');
            }
            $bank->user_id=$this->auth->id;
            $result = $bank->allowField(true)->validate('Bank.edit')->save($request,['id'=>$id]);
            if(false === $result){
                $this->error($bank->getError());
            }
            $this->success('修改成功',url('user/getbanks'));
        }

        return $this->view->fetch('',['info'=>$info]);

     }
     /**
     * 删除银行卡
     * 
     * @param int $id 索引
     */
    public function delbank()
    {
        
        $id = $this->request->request('id');
        if (empty($id)) {
            $this->error('请传入id ');
        }
        $bank = Bank::get(['user_id'=>$this->auth->id,'id'=>$id]);
        if ($bank->default==1) {
            $this->error('无法删除默认银行卡');
        }
        $bank->delete();
        $this->success('删除成功');
    }

    /**
     * 修改会员个人信息 某字段
     * @ApiParams   (name="field", type="string", required=true, description="要修改的字段 nickname,realname,idcard,alipay,wechatwallet,bio,avatar,gender")
     * @ApiParams   (name="value", type="string", required=true, description="要修改的字段值")
     */
    public function profilesingle()
    {
        $fieldallow = ['nickname','realname','idcard','alipay','wechatwallet','bio','avatar','gender','mobile','email','eth'];
        $user = $this->auth->getUser();
        $field = $this->request->request('field');
        if (!in_array($field, $fieldallow)) {
            $this->error('字段不允许修改');
        }
        $value = $this->request->request('value','','trim');
        if (empty($value)) {
            $this->error('请填写');
        }
        if ($field == 'eth') {
            $captcha = $this->request->request("captcha");
            $userinfo = $this->auth->getUserInfo();
            if ($userinfo['mobile']) {
                $ret = Smslib::check($userinfo['mobile'], $captcha, 'USDT');
                if (!$ret) {
                    $this->error(__('验证码不正确'));
                }
            }else{
                $this->error(__('验证码不正确'));
            }
        }
        $user->$field = $value;
        $user->save();
        $this->success('成功');
    }
    public function address(){
          
        $address = new Address();
        $addresss=$address->where('status',1)->where('user_id',$this->auth->id)->order('default desc,id desc')->select();
        return $this->view->fetch('',['list'=>$addresss]);
    }
    public function address_add(){
       if ($this->request->isPost()) {
           $address = new Address();
             $request=array();
            $request['consignee']=$this->request->post('consignee');
            $request['phone']=$this->request->post('phone');
            $request['province']=$this->request->post('province');
            $request['city']=$this->request->post('city');
            $request['district']=$this->request->post('district');
            $request['detail']=$this->request->post('detail');
            $request['default']=$this->request->post('default');
            $token = $this->request->post('__token__'); 
             $rule = [
                'consignee'   => 'require|length:2,5',
                'phone'   => 'require|length:11',
                'province' => 'require|length:2,10',
                'city' => 'require|length:2,10',
                'district' => 'require|length:2,10',
                'detail' => 'require|length:2,30',
                '__token__'     => 'token',
            ];

            $msg = [
            ];
            $data = [
                'consignee'   => $request['consignee'],
                'phone'   => $request['phone'],
                'province' => $request['province'],
                'city' => $request['city'],
                'district' => $request['district'],
                'detail' => $request['detail'],
                '__token__'     => $token,
            ];
            $field = [
                'consignee'   => __('收货人'),
                'phone'   => __('联系电话'),
                'province' => __('省'),
                'city'   => __('市'),
                'district'   => __('区'),
                'detail' => __('详细地址'),
            ];
            $validate = new Validate($rule, $msg, $field);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                return FALSE;
            }
            $address->user_id=$this->auth->id;
            $result = $address->save($request);
            if(false === $result){
                $this->error($address->getError());
            }
            $this->success('增加成功',url('user/address'));
       }
      return $this->view->fetch();  
    }
    public function editaddress(){
          $id =$_GET['id'];
         if ($this->request->isPost()) {
            $request=array();
            $request['consignee']=$this->request->post('consignee');
            $request['phone']=$this->request->post('phone');
            $request['province']=$this->request->post('province');
            $request['city']=$this->request->post('city');
            $request['district']=$this->request->post('district');
            $request['detail']=$this->request->post('detail');
            $request['default']=$this->request->post('default');
            $token = $this->request->post('__token__'); 
             $rule = [
                'consignee'   => 'require|length:2,5',
                'phone'   => 'require|length:11',
                'province' => 'require|length:2,10',
                'city' => 'require|length:2,10',
                'district' => 'require|length:2,10',
                'detail' => 'require|length:2,30',
                '__token__'     => 'token',
            ];

            $msg = [
            ];
            $data = [
                'consignee'   => $request['consignee'],
                'phone'   => $request['phone'],
                'province' => $request['province'],
                'city' => $request['city'],
                'district' => $request['district'],
                'detail' => $request['detail'],
                '__token__'     => $token,
            ];
            $field = [
                'consignee'   => __('收货人'),
                'phone'   => __('联系电话'),
                'province' => __('省'),
                'city'   => __('市'),
                'district'   => __('区'),
                'detail' => __('详细地址'),
            ];
            $validate = new Validate($rule, $msg, $field);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                return FALSE;
            }
            $address = new Address();
            if (empty($id)) {
                $this->error('请传入id ');
            }
            $address->user_id=$this->auth->id;
            $result = $address->save($request,['id'=>$id]);
            if(false === $result){
                $this->error($address->getError());
            }
            $this->success('修改成功',url('user/address'));
        }
        $address = new Address();  
        $info=$address->where('user_id',$this->auth->id)->where('id',$id)->find();
        if (!$info) {
            $this->error('不是你的地址！');
        }
       
        return $this->view->fetch('',['info'=>$info]); 
    }
      /**
     * 发送验证码
     * @param  [type] $event [description]
     * @return [type]        [description]
     */
    public function sendCode()
    {
        $event = $this->request->request('event');
        $userinfo = $this->auth->getUserInfo();
        if ($userinfo['mobile']) {
            $ret = Smslib::send($userinfo['mobile'], NULL, $event);
        }elseif($userinfo['email']){
            $ret = Emslib::send($userinfo['userinfo'], NULL, $event);
        }else{
             $this->error(__('发送失败 code：001'));
        }
        if ($ret) {
            $this->success(__('发送成功'));
        } else {
            $this->error(__('发送失败 code：002'));
        }
    }
      /**
     * 删除地址
     * 
     * @param int $id 索引
     */
    public function deladdress()
    {
        
        $id = $this->request->request('id');
        if (empty($id)) {
            $this->error('请传入id ');
        }
        $address = Address::get(['user_id'=>$this->auth->id,'id'=>$id]);
        if ($address->default==1) {
            $this->error('无法删除默认银行卡');
        }
        $address->delete();
        $this->success('删除成功');
    }
}
